// pages/shopping_mall/coupon/coupon_enable_send.js
var cf = require("../../../config.js");
var cf2 = require("../../../utils/config2");
var Zan = require('../../../youzan/dist/index');
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var token =  wx.getStorageSync('authName');
var baseHandle = require("../../template/baseHandle.js");
import Serv from './couponsServ';
var regeneratorRuntime = require("../../../lib/js/runtime-module.js")
//获取应用实例
var app = getApp();
Page(Object.assign({}, baseHandle, Zan.Toast, Zan.Tab,{

  /**
   * 页面的初始数据
   */
  data: {
    recordList:[],
    curPage:1,
    isBottom:false,
    isLoading:false,
    size:10,
    app: app,
    needUserInfo: true,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    nodata: false,
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    nomore: false,
    openid:"",
    couponsList:[],
    activeIndex:null,
    pageType:"myCoupon"//上一个页面的路由是首页还是个人中心
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
    var ctx = this;
    ctx.setData({
      openid: options.openid
    })
    app.getUserInfo(this, options, function (userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      ctx.getCouponsList();
    });
  },
  // 跳转优惠券转赠页面
  goCouponExamples: function () {
    wx.navigateTo({ url:'/pages/biz/my/myCoupons/couponsExamples/couponsExamples'})
  },
  // 获取优惠券列表,pageType 上一个路由的类型，首页和个人中心所调用接口不一样  0 首页  1 个人中心
  async getCouponsList(params, type){
    let employee = wx.getStorageSync('employee');
    if(employee){
      let that = this;
      wx.request({
        url: `${cf2.default.dataCenter}zmzj/coupon/${employee.phone}`,//`${cf2.default.dataCenter}zmzj/coupon/${phone}`, //'http://10.73.159.105:8097/zmzj/coupon/15940067368',//
        header: {
          'content-type': 'application/json',
          token
        },
        success: function (res) {
          console.log(res.data);
          let couponsList = []
          for (let key in res.data) {
            if (res.data[key].data && res.data[key].data.length) {
              res.data[key].data.map(item => {
                item.productId = key;
                couponsList.push(item);
              })
            }
          }
          that.setData({ couponsList })

        }
      })
  
    }
   
    
  },
  // 去优惠券详情
  goCouponDetail: function (e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({ url:'/pages/biz/my/myCoupons/couponsDetail/couponsDetail?id='+id})
  },
  // （领取）子组件回调
  async receiveCoupon(e){
    let params = {
      pageNo: 1,
      pageSize: 10
    }
    let result = await Serv.receiveCoupon({ couponsConfigId: e.detail.id });
    if (result.success) {
      this.getCouponsList(params, 0);
      wx.showToast({ title: "领取成功"});
    }else{
      wx.showToast({ title: result.msg != 'null' ? result.msg : '领取失败', icon: "none" });
    }
  },
  getCoupons(){
    var ctx = this;
    if (ctx.data.isLoading || ctx.data.isBottom) {
      return;
    }
    wx.showLoading({
      title: '加载中'
    });
    ctx.setData({ isLoading: true });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/coupon/findSendEnableList',
      data: {
        cusmallToken: cusmallToken,
        openid: ctx.data.openid,
        start: (ctx.data.curPage - 1) * ctx.data.size,
        limit: ctx.data.size,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.hideLoading();
        var data = res.data;
        if (data.ret == 0) {
          var list = data.model.list;
          for (let item of list){
            if (item.effectStartTime) {
              item.effectStartTime = util.formatDate(new Date(item.effectStartTime));
            }
            if (item.effectEndTime) {
              item.effectEndTime = util.formatDate(new Date(item.effectEndTime));
            }
          }
          ctx.setData({
            recordList: ctx.data.recordList.concat(list),
            total: data.model.total
          });
          if (data.model.total == ctx.data.recordList.length) {
            ctx.setData({
              isBottom: true
            });
          }
        } else {
          
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.msg
          })
        }
      },
      complete(){
        ctx.setData({
          isLoading: false
        })
      }
    });
  },
  selectCoupon(e){
    var coupon = e.currentTarget.dataset;
    let ctx = this;
    let pages = getCurrentPages();//当前页面
    let prevPage = pages[pages.length - 2];//上一页面
    ctx.setData({activeIndex:coupon.index});
    wx.showModal({
      title: '提示',
      content: `确定发送此优惠券？`,
      success (res) {
        if (res.confirm) {
          prevPage.setData({
            sendCoupon: coupon.item
          });
          prevPage.handleSendCouponMsg(5);
          wx.navigateBack({
            delta: 1
          });
        } else if (res.cancel) {
         
        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let params = {
      // accountId:'123',
      pageNo: 1,
      pageSize: 10
    }

    let pages = getCurrentPages()
    var prevPage = pages[pages.length - 2].route;  //上一个页面
    console.log(prevPage,'prevPage')
    //如果是首页过来的
    if (prevPage == 'pages/biz/index/index' || prevPage == 'pages/biz/buildingDetail/buildingDetail') {
      this.setData({ pageType: 'index' });//首页
      wx.setNavigationBarTitle({title:"优惠券"});
    } else {
      this.setData({ pageType: 'myCoupon' });//个人中心
      wx.setNavigationBarTitle({ title: "我的优惠券" });
    }
    this.getCouponsList(params, 0);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
   /* let ctx = this;
    if (ctx.data.isLoading) {
      return;
    }
    ctx.setData({ curPage: ctx.data.curPage + 1 });
    ctx.getCoupons();*/
    let total = parseInt(this.data.couponsList.total) // 总页数
    let totalPage = 1 // 总页数
    if (total%10 === 0) {
      totalPage = parseInt(total/10)
    } else {
      totalPage = parseInt(total/10) + 1
    }
    let pageNo = parseInt(this.data.couponsList.pageNo) // 当前页数
    if (pageNo < totalPage && (pageNo + 1) <= totalPage) { // 如果当前条数小于总条数
      let params = {
        pageNo: pageNo + 1,
        pageSize: 10
      }
      this.getCouponsList(params, 1)
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
}))